﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using WMSmanagement.IBaseService.PurchasingManagement;
using WMSmanagement.IBaseService.PurchasingManagement.Dto;
using WMSmanagement.Model;

namespace WMSmanagement.BaseService
{
    [ApiExplorerSettings(GroupName = "闫汪洋")]
    public class ProcurementService : ApplicationService, IProcurementService
    {
        private readonly IRepository<Procurement, int> _procurementrepository;
        private readonly IRepository<Products, int> _productsrepository;
        private readonly IRepository<PurchaseDetails, int> _purchaseDetailsrepository;
        public ProcurementService(IRepository<Procurement, int> procurementrepository, IRepository<Products, int> productsrepository, IRepository<PurchaseDetails, int> purchaseDetailsrepository)
        {
            _procurementrepository = procurementrepository;
            _productsrepository = productsrepository;
            _purchaseDetailsrepository = purchaseDetailsrepository;
        }
        /// <summary>
        /// 添加采购
        /// </summary>
        /// <param name="addProcurementDto"></param>
        /// <returns></returns>
        public async Task<int> AddProcurementAsync(AddProcurementDto addProcurementDto)
        {
            var procurement = addProcurementDto.MapTo<Procurement>();
            procurement.CreateDate = DateTime.Now;
            procurement.State = "全部入库";
            procurement.IsEntry = false;
            procurement.ReturnGood = "正常";
            int res = await _procurementrepository.InsertAsync(procurement) != null ? 1 : 0;
            var purchaseDetails = new List<PurchaseDetails>();
            foreach (var item in addProcurementDto.purchasedetails)
            {
                var purchaseDetail = new PurchaseDetails()
                {
                    ProductCode = item.Ids,
                    PurchaseOrderCode = addProcurementDto.ProcurementCode,
                    Quantity = item.Nums,
                };
                purchaseDetails.Add(purchaseDetail);
            }
            res += _purchaseDetailsrepository.InsertManyAsync(purchaseDetails) != null ? 1 : 0;
            return res;
        }
        /// <summary>
        /// 删除采购
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> DeleteProcurementAsync(int id)
        {
            var procurement = await _procurementrepository.GetAsync(id);
            int res = _procurementrepository.DeleteAsync(procurement) != null ? 1 : 0;
            var purchasedetails = await _purchaseDetailsrepository.GetListAsync(c => c.ProductCode == procurement.ProcurementCode);
            res += _purchaseDetailsrepository.DeleteManyAsync(purchasedetails) != null ? 1 : 0;
            return res;
        }
        /// <summary>
        /// 获取采购列表
        /// </summary>
        /// <param name="procurementCode"></param>
        /// <param name="productCode"></param>
        /// <param name="productName"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<string> GetProcurementAsync(string procurementCode = "", string productCode = "", string productName = "", string state = "", int page = 1, int limit = 10)
        {
            var procurements = (from a in await _purchaseDetailsrepository.GetListAsync()
                                join b in await _procurementrepository.GetListAsync() on a.PurchaseOrderCode equals b.ProcurementCode
                                join c in await _productsrepository.GetListAsync() on a.ProductCode equals c.ProductCode
                                select new ProcurementDto
                                {
                                    Id = a.Id,
                                    ProcurementCode = b.ProcurementCode,
                                    SupplierCode = b.SupplierCode,
                                    SupplierName = b.SupplierName,
                                    CreateDate = b.CreateDate,
                                    State = b.State,
                                    IsEntry = b.IsEntry,
                                    ReturnGood = b.ReturnGood,
                                    ProductCode = c.ProductCode,
                                    ProductName = c.ProductName,
                                    ProductSpecification = c.ProductSpecification,
                                    Unit = c.Unit,
                                    UnitPrice = c.UnitPrice,
                                    Quantity = a.Quantity,
                                }).ToList();
            var result = procurements
                .WhereIf(!string.IsNullOrEmpty(procurementCode), c => c.ProcurementCode.Contains(procurementCode))
                .WhereIf(!string.IsNullOrEmpty(productCode), c => c.ProductCode.Contains(productCode))
                .WhereIf(!string.IsNullOrEmpty(productName), c => c.ProductName.Contains(productName))
                .WhereIf(!string.IsNullOrEmpty(state), c => c.State == state)
                .Skip((page - 1) * limit)
            .Take(limit)
            .ToList();
            return JsonConvert.SerializeObject(new { code = "0", data = result, msg = "成功", count = procurements.Count });
        }
        /// <summary>
        /// 修改采购
        /// </summary>
        /// <param name="procurementDto"></param>
        /// <returns></returns>
        public async Task<int> UpdateProcurementAsync(UpdateProcurementDto updateProcurementDto)
        {
            var procurement = updateProcurementDto.MapTo<Procurement>();
            int res = await _procurementrepository.UpdateAsync(procurement) != null ? 1 : 0;
            var purchasedetails = await _purchaseDetailsrepository.GetListAsync(c => c.ProductCode == procurement.ProcurementCode);
            res += _purchaseDetailsrepository.DeleteManyAsync(purchasedetails) != null ? 1 : 0;
            var purchaseDetails = new List<PurchaseDetails>();
            foreach (var item in updateProcurementDto.purchasedetails)
            {
                var purchaseDetail = new PurchaseDetails()
                {
                    ProductCode = item.Ids,
                    PurchaseOrderCode = updateProcurementDto.ProcurementCode,
                    Quantity = item.Nums,
                };
                purchaseDetails.Add(purchaseDetail);
            }
            res += _purchaseDetailsrepository.InsertManyAsync(purchaseDetails) != null ? 1 : 0;
            return res;
        }
        /// <summary>
        /// 产品列表
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="productName"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<string> GetProductsAsync(string productCode = "", string productName = "", int page = 1, int limit = 10)
        {
            var products = await _productsrepository.GetListAsync();
            var result = products
                .WhereIf(!string.IsNullOrEmpty(productCode), c => c.ProductCode.Contains(productCode))
                .WhereIf(!string.IsNullOrEmpty(productName), c => c.ProductName.Contains(productName))
                .Skip((page - 1) * limit)
                .Take(limit)
                .ToList();
            return JsonConvert.SerializeObject(new { code = "0", data = result, msg = "成功", count = products.Count });
        }
    }
}
